package vn.cuhanh.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import vn.cuhanh.HeroDetailActivity;
import vn.cuhanh.R;
import vn.cuhanh.ShareActivity;
import vn.cuhanh.bean.Hero;
import vn.cuhanh.bean.ShareInfo;
import vn.cuhanh.handler.HeroesReaderHandler;
import vn.cuhanh.utils.HelperFunc;
import vn.cuhanh.utils.ShareZingMe;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class HeroesFragment extends BasicFragment {
	
	private static String GA_CATEGORY = "Heroes_fragment";
	
	private View view;
	private ArrayList<Hero> heroesInfo = new ArrayList<Hero>();
	private ArrayList<Hero> displayedHeroesInfo;
	private HeroAdapter adapter;
	private Handler handler;

	public static HeroesFragment newInstance(Context ctx) {
		return new HeroesFragment(ctx);
	}

	public HeroesFragment(Context ctx) {
		super(ctx);
		handler = new Handler();
	}

	public HeroesFragment() {
		super();
		handler = new Handler();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// setUserVisibleHint(true);
	}

	@Override
	public void onPause() {
		super.onPause();
		// HelperFunc.unbindDrawables(view);
		// System.gc();
	}

	@Override
	public void onDestroy() {

		super.onDestroy();
	}
	
	public void loadHeroesData() throws IOException {
		if(heroesInfo != null && !heroesInfo.isEmpty()) {
			return;
		}
		try {
			InputStream is = ctx.getAssets().open("heroes.xml");
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader xmlreader = parser.getXMLReader();
			HeroesReaderHandler theRssHandler = new HeroesReaderHandler(heroesInfo);
	
			xmlreader.setContentHandler(theRssHandler);
			InputSource inputSource = new InputSource(is);
			xmlreader.parse(inputSource);
		} catch (Exception e) {
			HelperFunc.readStackTrace(e);
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		try {
			view = inflater.inflate(R.layout.heroes_fragment, null);
			if (ctx == null || view == null) {
				if (isAdded()) {
					ctx = getActivity();
				} else {
					return view;
				}
			}
			initBtnSearch();
			initListHeroesType();
			loadHeroesData();
			initListHeroes();
			Log.d("Heroes fragment", String.valueOf(heroesInfo.get(4).getName()));
			// manually start loading stuff in the first tab
			return view;
		} catch (InflateException e) {
			HelperFunc.readStackTrace(e);
		} catch (Exception e) {
			HelperFunc.readStackTrace(e);
		}
		return null;
	}
	
	public void initBtnSearch(){
		ImageButton btnSearch = (ImageButton) view.findViewById(R.id.heroes_search_btn);
		btnSearch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(ctx, GA_CATEGORY, "btn_search_press", "btn_search_press");
				EditText txtSearch = (EditText)view.findViewById(R.id.heroes_search_edit_text);
				String keyword = txtSearch.getText().toString();
				searchHeroes(keyword);
			}
		});
	}
	
	public void updateListHeroes(ArrayList<Hero> heroes) {
		if(heroes == null) {
			return;
		}
		TextView txtNoHero = (TextView) view.findViewById(R.id.heroes_txt_no_hero);
		ListView listHero = (ListView) view.findViewById(R.id.heroes_list);
		if(heroes.isEmpty()) {
			txtNoHero.setVisibility(View.VISIBLE);
			listHero.setVisibility(View.GONE);
			return;
		} else {
			txtNoHero.setVisibility(View.GONE);
			listHero.setVisibility(View.VISIBLE);
		}
		adapter.setHeroesInfo(heroes);
		adapter.notifyDataSetChanged();
	}
	
	public void searchHeroes(String keyword) {
		if(keyword == null || keyword.isEmpty()) {
			return;
		}
		keyword = HelperFunc.slugify(keyword);
		ArrayList<Hero> tmpHeroList = new ArrayList<Hero>();
		for (Hero hero : heroesInfo) {
			String heroName = HelperFunc.slugify(hero.getName());
			if(heroName.indexOf(keyword) > -1) {
				tmpHeroList.add(hero);
			}
		}
		updateListHeroes(tmpHeroList);
	}
	
	public void filterHeroesByType(int typeId) {
		if(typeId == 0) {
			updateListHeroes(heroesInfo);
			return;
		}
		ArrayList<Hero> tmpHeroList = new ArrayList<Hero>();
		for (Hero hero : heroesInfo) {
			if(hero.getNation() == typeId) {
				tmpHeroList.add(hero);
			}
		}
		updateListHeroes(tmpHeroList);
	}
	
	public void initListHeroesType(){
		Spinner spinnerHeroesType = (Spinner) view.findViewById(R.id.heroes_dropdown_type);
		String[] strTypes = ctx.getResources().getStringArray(R.array.hero_types);
		ArrayList<CharSequence> listTypes = new ArrayList<CharSequence>();
		for (String string : strTypes) {
			listTypes.add(string);
		}
		
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(ctx, R.layout.heroes_spinner_type_item, R.id.heroes_spinner_type_item_txt, listTypes); 
		adapter.setDropDownViewResource(R.layout.heroes_spinner_type_dropdown_item);
		spinnerHeroesType.setAdapter(adapter);
		spinnerHeroesType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				filterHeroesByType(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				Log.d("heroes", "Spinner nothing selected");
			}
		});
		
	}
	
	public void initListHeroes() {
		ListView list = (ListView) view.findViewById(R.id.heroes_list);
		adapter = new HeroAdapter(ctx, R.id.heroes_list_item_name, heroesInfo);
		list.setAdapter(adapter);
//		list.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
//					long arg3) {
//				// TODO Auto-generated method stub
//				try {
//					Hero hero = heroesInfo.get(position);
//					String strHero = HelperFunc.Serialize(hero);
//					Log.d("start intent", "hero info: " + strHero);
////					Intent intent = new Intent(ctx, HeroDetailActivity.class);
////					intent.putExtra("heroInfo", strHero);
////					startActivity(intent);
////					Log.d("start intent", "hero info: " + strHero);
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					HelperFunc.showSimpleAlertDialog(ctx, "title", "message", "Huy", null, null, null, true);
//					HelperFunc.readStackTrace(e);
//				}
//			}
//		});
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setRetainInstance(true);
	}
	
	public class HeroAdapter extends ArrayAdapter<Hero> {
		private List<Hero> heroesInfo;

		public HeroAdapter(Context context, int textViewResourceId,
				List<Hero> objects) {
			super(context, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
			this.heroesInfo = objects;
		}
		
		@Override
		public int getCount() {
			return this.getHeroesInfo().size();
		}
		
		@Override
		public View getView(int position, View v, ViewGroup parent) {
			if(v == null) {
				LayoutInflater inflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.heroes_list_item, null);
			}
			final Hero hero = this.getHeroesInfo().get(position);
			ImageView imageView = (ImageView)v.findViewById(R.id.heroes_list_item_avatar);
			try {
				imageView.setImageBitmap(HelperFunc.getBitmapFromAsset(ctx, hero.getAvatar()));
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				HelperFunc.readStackTrace(e1);
			} catch (Exception e) {
				// TODO: handle exception
				HelperFunc.readStackTrace(e);
			}
//			int imageResId = ctx.getResources().getIdentifier(hero.getAvatar(), "drawable", ctx.getPackageName());
//			imageView.setImageResource(imageResId);
			TextView textView = (TextView)v.findViewById(R.id.heroes_list_item_name);
			textView.setText(hero.getName());
			ImageView imageRate = (ImageView)v.findViewById(R.id.heroes_list_item_rate);
			String rateFileName = "rating_" + hero.getRate();
			int rateFileNameResId = ctx.getResources().getIdentifier(rateFileName, "drawable", ctx.getPackageName());
			imageRate.setImageResource(rateFileNameResId);
			Button btnShare = (Button)v.findViewById(R.id.heroes_list_item_btn_share);
			btnShare.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					HelperFunc.trackEvent(ctx, "share", "btn_share_press", "Share_hero_on_list");
					ShareActivity.shareInfo = new ShareInfo(
							ctx.getResources().getString(R.string.shareHeroName).replace("hero_name", hero.getName()), 
							ctx.getResources().getString(R.string.shareHeroTitle).replace("hero_name", hero.getName()), 
							ctx.getResources().getString(R.string.shareHeroDescription)
								.replace("hero_name", hero.getName())
								.replace("funny_phrase", ShareZingMe.getRandomFunnyPhrase(ctx)), 
							hero.getAvatarUrl(), 
							hero.getAvatarUrl(), 
							hero.getFullInfoWebUrl(), 
							ctx.getResources().getString(R.string.shareHeroState + hero.getId()),
							getResources().getInteger(R.integer.actionIdShareHeroInfo));
					Intent intent = new Intent(ctx, ShareActivity.class);
					startActivity(intent);
//					ShareZingMe.confirmSharingZingMe(ctx, ShareActivity.shareInfo);
				}
			});
			v.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					HelperFunc.trackEvent(ctx, GA_CATEGORY, "hero_item_press", "Hero_item_press");
//					final View v = view;
					try {
						String strHero = HelperFunc.Serialize(hero);
						Intent intent = new Intent(ctx, HeroDetailActivity.class);
						intent.putExtra("heroInfo", strHero);
						startActivity(intent);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						HelperFunc.showSimpleAlertDialog(ctx, "title", "message", "Huy", null, null, null, true);
						HelperFunc.readStackTrace(e);
					}
				}
			});
			return v;
		}

		public List<Hero> getHeroesInfo() {
			return heroesInfo;
		}

		public void setHeroesInfo(List<Hero> heroesInfo) {
			this.heroesInfo = heroesInfo;
		}
	}
	
}
